<?php 

function aDecode($string = '', $skey = 'abcde') {
    $strArr   = str_split(str_replace(array('O0O0O', 'o000o', 'oo00o'), array('=', '+', '/'), $string), 2);
    $strCount = count($strArr);
    foreach (str_split($skey) as $key => $value) {
        $key <= $strCount && isset($strArr[$key]) && $strArr[$key][1] === $value && $strArr[$key] = $strArr[$key][0];
    }
    return base64_decode(join('', $strArr));
}

function curlGet($url, $refer = "") {
    $url = $url;
    $ch = curl_init();
    
    curl_setopt($ch, CURLOPT_URL, $url);
    
    if (!empty($url)) {
        $header = array (
            "Referer:{$refer}"
        );
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    }
    
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ch, CURLOPT_TIMEOUT, 5);
    $content = curl_exec($ch);
    if ($content == false) {
        header("aerror:curl" . json_encode(curl_error($ch)));
    }
    curl_close($ch);
    return $content;
}

function parseUrl($content, $config) {
    $xml        = simplexml_load_string($content);
    $xmljson    = json_encode($xml);
    $xml        = json_decode($xmljson,true);
    
    $url        = $xml['dict']['array']['dict']['array']['dict'][0]['string'][1];
    return $url;
}

function getUrl($config) {
    $url    = "";
    
    $key    = md5($config['url']);
    $time   = time();
    $date   = date("Y-m-d");
    
    $path   = "data/{$date}-{$key}.txt";
    
    
    $filedata   = file_get_contents($path);

    if ($filedata && !empty($filedata)) {
        $data = json_decode($filedata, true);
        if (!empty($data['time']) && $time - $data['time'] <= $config['validtime']) {
            $last = $time - $data['time'];
            header("alast:{$last}");
            $url = $data['url'];
        }
    }
    
    if (empty($url)) {
        $content = curlGet($config['url'], $config['refer']);
        $url     = parseUrl($content, $config);
        
        if (!empty($url)) {
            $data = array(
                'time'  => $time,
                'url'   => $url
            );
            
            $result = file_put_contents($path, json_encode($data));
        } else {
            header("aerror:fail-1");
        }
    }
    
    
    if (empty($url)) {
        header("aerror:fail-2");
    }

    return $url;
}

require "config.php";

$url        = aDecode($_GET['ukey']);
$type       = $_GET['type'];

$config     = array();


if (!empty($url) || !empty($type)) {
    $config = !empty($configList[$type]) ? $configList[$type] : $configDefault;
    
    $config['url'] = $url;
    
    $url = getUrl($config);
    if (!empty($url)) {
        header("Location: {$url}");
    }
    
} else {
    header("aerror:fail-0");
}

